function parse(str) {
  let val
  try {
    val = JSON.parse(str)
  } catch (err) {
    val = null
  }
  return val
}

function stringify(obj) {
  let val
  try {
    val = JSON.stringify(obj)
  } catch (error) {
    val = null
  }
  return val
}

export default function storage() {
  function setItem(key, value) {
    value = stringify(value)
    window.localStorage.setItem(key, value)
  }

  function getItem(key) {
    let val = window.localStorage.getItem(key)
    if (val) val = parse(val)
    return val
  }

  return {
    setItem,
    getItem
  }
}
